package ds_industry_2025.industry.gy_09.T3

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
/*
    3、编写scala代码，使用Spark根据dws层的machine_produce_per_avgtime表,获取各设备生产耗时最长的两个产品的用时,将计算结果
    存入MySQL数据库shtd_industry的machine_produce_timetop2表中（表结构如下），然后在Linux的MySQL命令行中根据设备id降序
    排序，查询出前2条，将SQL语句复制粘贴至客户端桌面【Release\任务B提交结果.docx】中对应的任务序号下，将执行结果截图粘贴至客户
    端桌面【Release\任务B提交结果.docx】中对应的任务序号下；
 */
object t6 {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder()
      .master("local[*]")
      .appName("t1")
      .config("hive.exec.dynamic.partition.mode", "nonstrict")
      .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions", "org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .config("spark.sql.legacy.parquet.datetimeRebaseModeInRead", "LEGACY")
      .enableHiveSupport()
      .getOrCreate()



    spark.table("dws.machine_produce_per_avgtime")
      .createOrReplaceTempView("data")

    val r1 = spark.sql(
      """
        |select
        |*
        |from(
        |select distinct
        |produce_machine_id as machine_id,
        |produce_time,
        |row_number() over(partition by produce_machine_id order by produce_time desc) as row
        |from data
        |) as
        |where row < 3
        |""".stripMargin)

    //  todo 方法1
    val result1 = r1.groupBy("machine_id")
      .agg(
        max("produce_time").as("first_time"),
        min("produce_time").as("second_time")
      ).distinct()

    result1.show

    //  todo 方法2
    val t1 = r1.filter(col("row") === 1)
      .withColumn("row", lit("first_time"))
      .groupBy("machine_id")
      .pivot("row")
      .agg(first("produce_time"))
      .distinct()


    val t2 = r1.filter(col("row") === 2)
      .withColumn("row", lit("second_time"))
      .groupBy("machine_id")
      .pivot("row")
      .agg(first("produce_time"))
      .distinct()

    val result2 = t1.join(t2,"machine_id")

    result2.show


    spark.close()
  }

}
